package com.manbu.live.msg.provider.service.impl;

import ch.qos.logback.core.testUtil.RandomUtil;
import com.manbu.live.farmework.redis.starter.keys.MsgProviderCacheKeyBuilder;
import com.manbu.live.farmework.redis.starter.keys.RedisKeyBuilder;
import com.manbu.live.id.generate.interfaces.IdGenerateRpc;
import com.manbu.live.msg.dto.MsgCheckDTO;
import com.manbu.live.msg.enums.MsgSendResultEnum;
import com.manbu.live.msg.provider.config.ThreadManager;
import com.manbu.live.msg.provider.dao.mapper.SmsMapper;
import com.manbu.live.msg.provider.dao.po.SmsPO;
import com.manbu.live.msg.provider.service.ISmsService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author hanWang
 * @Title:
 * @Package
 * @Description:
 * @date 2024/1/281:46 AM
 */
@Service
public class SmsServiceImpl implements ISmsService {
    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
    @Resource
    private  MsgProviderCacheKeyBuilder msgProviderCacheKeyBuilder;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private SmsMapper mapper;
    @DubboReference
    private IdGenerateRpc idGenerateRpc;
    @Override
    public MsgSendResultEnum sendMessage(String phone) {
        if (StringUtils.isEmpty(phone)){
            return MsgSendResultEnum.MSG_PARAM_ERROR;
        }
        // 生成验证码 同一个验证码不能重复发
        // 借助redis 实现验证码过期
        String msgLoginCodeKey = msgProviderCacheKeyBuilder.buildMsgLoginCodeKey(phone);
        // 如果同一个手机号防止重复发送
        if (redisTemplate.hasKey(msgLoginCodeKey)){
            logger.warn("该手机号发送验证码过于频繁... phone is {}",phone);
            return MsgSendResultEnum.SEND_FAIL;
        }
        int code = RandomUtils.nextInt(100000,999999);
        ThreadManager.commonAsyncThreadPool.execute(()->{
            boolean sendMsgStatus = this.mockSendMsg(phone, code);
            //
            if (sendMsgStatus){
                // 插入记录
                insertOne(phone,code);
            }
        });
        // 发送验证码

        // 记录验证码发送记录
        return MsgSendResultEnum.SEND_SUCCESS;
    }

    @Override
    public MsgCheckDTO checkLoginCode(String phone, Integer code) {
        //  参数校验
        if (StringUtils.isEmpty(phone)||code==null||code<100000){
            return new MsgCheckDTO(false,"参数异常。。。");
        }
        String msgLoginCodeKey = msgProviderCacheKeyBuilder.buildMsgLoginCodeKey(phone);
        if (!redisTemplate.hasKey(msgLoginCodeKey)){
            return new MsgCheckDTO(false,"验证码已过期");
        }
        Integer redisCode = (Integer) redisTemplate.opsForValue().get(msgLoginCodeKey);

        if (code==redisCode){
            redisTemplate.delete(msgLoginCodeKey);
            return new MsgCheckDTO(true,"验证码校验成功");
        }
        // redis 验证验证码
        return new MsgCheckDTO(false,"验证码校验失败");
    }

    @Override
    public void insertOne(String phone, Integer code) {
        SmsPO smsPO = new SmsPO();
        Long l = idGenerateRpc.geSeqId(1);

        smsPO.setId(l);
        smsPO.setCode(code);
        smsPO.setPhone(phone);
        mapper.insert(smsPO);

    }

    /**
     * 模拟发送短信
     * @param phone
     * @param code
     * @return
     */
    private boolean mockSendMsg(String phone,Integer code){

        try {
            logger.info("================开始发送验证码============");
            Thread.sleep(1000);
            logger.info("================验证码发送成功============");
            return true;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
